/*
 * @Author: wuzhouhai wzh200x@126.com
 * @Date: 2024-04-12 14:20:13
 * @LastEditors: wuzhouhai wzh200x@126.com
 * @LastEditTime: 2024-04-12 14:31:16
 * @FilePath: \phoenix-client-damo\assets\src\phoenix\net\webSocketClient\webSocketClient.ts
 * @Description: 
 */
export class WebSocketClient {
    private _ws: WebSocket;

    constructor(url: string) {
        this._ws = new WebSocket(url);
    }

    private onOpen(event: Event) {
        console.log('WebSocket connected:', event);
        // 可以在这里添加连接成功后的回调函数或通知
      }
    
      private onMessage(event: MessageEvent) {
        const data = JSON.parse(event.data); // 假设服务器发送的是JSON格式数据
        console.log('Received message:', data);
        // 可以在这里解析并处理接收到的消息
      }
    
      private onError(error: Event | Error) {
        console.error('WebSocket error:', error);
        // 可以在这里添加错误处理逻辑
      }
    
      private onClose(event: CloseEvent) {
        console.log('WebSocket closed:', event);
        // 可以在这里添加断开连接后的回调函数或通知
      }
    
      public send(data: any) {
        if (this._ws.readyState === WebSocket.OPEN) {
          this._ws.send(JSON.stringify(data)); // 假设发送的是JSON格式数据
        } else {
          console.warn('WebSocket is not open, cannot send message.');
        }
      }
    
      public close() {
        this._ws.close();
      }
}